﻿namespace WPFDBBrowser.UserControls
{
    using System.Windows;
    using WPFDBBrowser.Framework;
    using WPFDBBrowser.Settings;
    using WPFDBBrowser.Windows;
    using System.Threading;
    using Amib.Threading;
    using System.Windows.Input;

    /// <summary>
    /// Interaction logic for DBTreeView.xaml
    /// </summary>
    public partial class QueryEditor : UserControlBase<QueryEditorPresenter, IQueryEditor>, IQueryEditor
    {
        public static RoutedCommand _runQuery = new RoutedCommand();
        
        public QueryEditor()
            : this(null)
        {
        }

        public QueryEditor(string instanceName)
            : base(instanceName)
        {
            this.InitializeComponent();
        }

        protected override void RegisterCommands(Window window)
        {
            base.RegisterCommands(window);
            window.CommandBindings.Add(new CommandBinding(_runQuery, ExecutedRunQueryCommand));
            this.buttonNewQuery.Command = _runQuery;
        }
        #region IQueryEditor Members

        private void ExecutedRunQueryCommand(object sender,
            ExecutedRoutedEventArgs e)
        {
        }

        public void AddQuery(string query, bool select)
        {
            this.aedQueryEditor.Dispatcher.Invoke(new Action(() =>
                {
                    // Remember start of selection + 2 new chars for extra lines
                    int selectionStart = string.IsNullOrEmpty(this.aedQueryEditor.Text) ? 0 :
                        this.aedQueryEditor.Text.Length + 2;
                    if (!string.IsNullOrEmpty(this.aedQueryEditor.Text))
                        this.aedQueryEditor.Text += "\n\n";
                    // Add new query
                    this.aedQueryEditor.Text += query;
                    // move caret to the end
                    //this.aedQueryEditor.CaretOffset = aedQueryEditor.Text.Length;
                    if (select)
                    {
                        // and finaly select inserted text
                        //this.aedQueryEditor.SelectionLength = 0;
                        //this.aedQueryEditor.SelectionStart = selectionStart;
                        //this.aedQueryEditor.SelectionLength = query.Length;
                        this.aedQueryEditor.Select(selectionStart, query.Length);
                    }
                    // scroll to end of document, where is added text
                    this.aedQueryEditor.ScrollToEnd();
                }));
        }

        #endregion

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }
    }
}
